package com.estacionamientos

import javax.mail.internet.MimeMessage
import org.springframework.mail.MailException
import org.springframework.mail.MailSender
import org.springframework.mail.SimpleMailMessage
import org.springframework.mail.javamail.MimeMessageHelper

class EmailService {
	MailSender mailSender
	MimeMessageHelper mimeMessageHelper

    static transactional = true

	def sendEmail(String to,String subject,String body){
		def email = [
			to: [ to],        // "to" expects a List, NOT a single email address
			subject: subject,
			text: body         // "text" is the email body
		]
		// sendEmails expects a List
		
		sendEmails([email])

	}
	
	
	def sendEmails(mails) {
		// Build the mail messages
		
		def messages = []
		for (mail in mails) {
			// Create a thread safe "sandbox" of the message
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			
			// use the true flag to indicate you need a multipart message
			helper.setTo(mail.to);
			helper.setFrom("matiaskochman@gmail.com")
			// use the true flag to indicate the text included is HTML
			helper.setText(mail.text, true);
			message.subject = mail.subject
			messages << message
		}
		// Send them all together
		
		try {
			//println "about to send ${messages.size()} messages to:n${messages.to.join('n')}"
			//mailSender.send(messages as SimpleMailMessage[])
			mailSender.send(messages as MimeMessage[])
			
		} catch (MailException ex) {
			println "Failed to send emails"
			ex.printStackTrace()
		}
	}

}
